package com.prizedraw.prize_draw.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import com.prizedraw.prize_draw.common.lang.Const;
import com.prizedraw.prize_draw.common.lang.Result;
import com.prizedraw.prize_draw.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;

@Slf4j
@RestController
public class AuthController extends BaseController{
    @Autowired
    Producer producer;

    /**
     * 获取验证码
     * @param httpServletRequest
     * @param httpServletResponse
     * @return
     * @throws IOException
     */
    @GetMapping("/captcha")
    public Result captcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        String code = producer.createText();
        String codekey = UUID.randomUUID().toString();

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image,"jpg",byteArrayOutputStream);
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";
        String base64Img = str + base64Encoder.encode(byteArrayOutputStream.toByteArray());
        //使用redis缓存放入验证码
        redisUtil.hset(Const.CAPTCHA_KEY,codekey,code,120);
        log.info("验证码：codekey---{},code---{}", codekey, code);
        return Result.succ(
                MapUtil.builder()
                        .put("codeKey",codekey)
                        .put("base64Img",base64Img)
                        .build()
        );
    }

    /**
     * 获取用户信息接口
     * @param principal
     * @return
     */
    @GetMapping("/sys/userInfo")
    public Result userInfo(Principal principal) {
        SysUser sysUser = sysUserService.getByUserId(principal.getName());
        log.info("用户登录成功，存入{}的为唯一principal.getName()",principal.getName());
        return Result.succ(MapUtil.builder()
                .put("id", sysUser.getId())
                .put("username", sysUser.getUserName())
                .map()
        );
    }
}
